import { HTTP_REQUEST_INFO } from '@/common/config.js';
import {
	isArray,
	isBoolean,
	isEmpty,
	isEmptyObj,
	isNull,
	isUnde
} from '../validate';
import { OT } from '../ktl-map';
import ktlcache from '../ktl-cache';
import { useKtluser } from '../ktl-user';
import CryptoJS from 'crypto-js';
import isObject from '../lodash/isObject';

/**
 * 封装请求方法
 * @param { object } options 请求参数
 * @description
 * - url 请求地址，必传
 * - data 传递的参数，非必传
 * - method 请求方式，非必传，默认值：POST
 * - header 请求头，非必传
 * - timeOut 超时时间(秒)，非必传
 */
export const request = (options: any) => {

	// 默认值
	const defaults = {
		url: '',
		data: {},
		method: 'POST',
		timeOut: HTTP_REQUEST_INFO.REQUEST_TIMEOUT,
	}

	// 自定义参数赋值
	for (let key in defaults) {
		if (!isEmpty(options[key])) {
			defaults[key] = options[key];
		}
	}

	// ms
	defaults.timeOut = defaults.timeOut * 1000;
	// console.log('promiss')
	return new Promise((resolve, reject) => {
		// console.log('defaults',defaults);
		// console.log('defaults',defaults);
		// #ifdef MP-WEIXIN
		defaults.url = 'https://nx5.abc5g.com/' + defaults.url
		// #endif
		uni.request({
			...defaults,
			success: (data: any) => {
				// console.log('data', data)
				resolve(data)
			},
			fail: reject
		} as any)
	})
}

/**
 * 数据处理类
 */
export class PostData {
	data = [];
	constructor() {}

	add(key: string, value: any) {
		try {
			const tmp = '{ "' + key + '": "' + value.toString()
				.replace(/\+/g, "%2b")
				.replace(/=/g, "%3d")
				.replace(/&/g, "%26")
				.replace(/'/g, '$*$*$')
				.replace(/\\/g, '$!$!$')
				.replace(/"/g, '$@$@$')
				.replace(/\n\r/g, "\\n\\r")
				.replace(/\r\n/g, "\\r\\n")
				.replace(/\r/g, "\\r")
				.replace(/\n/g, "\\n") + '" }';
			this.data.push(JSON.parse(tmp));
			return true;
		} catch (e) {
			console.log('参数中含有未能解析的字符!');
			console.log("未能解析的字符",key+":"+value);
			console.log(e);
			return false;
		}
	}

	addItem(item: any) {
		try {
			for (let key in item) {
				//console.log(key + ':' + item[key]);
				item[key] = item[key].toString().replace(/\+/g, "%2b")
					.replace(/=/g, "%3d")
					.replace(/&/g, "%26")
					.replace(/'/g, '$*$*$')
					.replace(/\\/g, '$!$!$')
					.replace(/"/g, '$@$@$')
					.replace(/\n\r/g, "\\n\\r")
					.replace(/\r\n/g, "\\r\\n")
					.replace(/\r/g, "\\r")
					.replace(/\n/g, "\\n");
			}
			this.data.push(item);
		} catch (e) {
			console.log(e);
		}

	}

	toString() {
		try {
			let result = JSON.stringify(this.data);
			result = result.replace(/"/g, "'"); //.replace(/###/g, '"');
			return result;
		} catch (e) {
			console.log(e);
		}
	}
}

// 是否是Command请求
function isCommandType(apiurl: string){
	const CommandTypes: string[] = [OT.Command, OT.CommandAddSet, OT.CommandSet];
	return CommandTypes.includes(apiurl);
}

// 生成请求数据
function makeSendData(action: string, data: any, mkey: string, others: any) {
	const ktlsetting = {
		islist: false,
		opuid: 0,
		mask: true,
		isqueue: false,
		routeid: ''
	}

	if (isBoolean(others)) {
		ktlsetting.islist = others;
	} else {
		for (let key in ktlsetting) {
			if (!isEmpty(others[key])) {
				ktlsetting[key] = others[key];
			}
		}
	}

	// try {
	// 	// 获取用户信息
	// const ktluser = useKtluser()
	// 	const user = ktluser.getUser(false);
	// 	ktlsetting.opuid = user.info.AccountId || ktlsetting.opuid;
	// } catch (e) {}
	
	let sendData: any = {
		ApiUrl: others.apiurl || OT.Command,
		Key: mkey
	};
	
	// 是否是Command请求
	const IsCommandType = isCommandType(sendData.ApiUrl);
	if(IsCommandType){
		sendData.Action = action;
		sendData.Parameters = '[]';
	}

	if (!isEmptyObj(data)) {
		const pd = new PostData()
		if (sendData.ApiUrl === OT.CommandAddSet) {
			// 数组，插入多条
			data.forEach((item: any) => pd.addItem(item));
			sendData.Parameters = pd.toString();
		} else if(IsCommandType){
			for (let key in data) {
				if(!pd.add(key, data[key])){
					console.log("无效的参数")
					return;
				}
			}
			sendData.Parameters = pd.toString();
		} else if(!isArray(data)){
			for (let key in data) {
				if(typeof(data[key]) == "object"){
					sendData[key] = JSON.stringify(data[key]);
				}else{
					sendData[key] = data[key];
				}
			}
		}
	}

	const header = {
		"Content-Type": "text/plain;charset=UTF-8"
	};
	
	let sendDataStr = '';
	for(let key in sendData){
		sendDataStr += (sendDataStr.length === 0 ? '' : '&') + key + '=' + sendData[key] 
	}

	//console.log('请求接口：' + sendData.ApiUrl)
	console.log('请求参数：' + sendDataStr)
	
	const KEY = CryptoJS.enc.Utf8.parse(mkey);
	const IV = CryptoJS.enc.Utf8.parse(mkey.substring(0, 16));
	
	let srcs = CryptoJS.enc.Utf8.parse(sendDataStr);
	let encrypted = CryptoJS.AES.encrypt(srcs, KEY, {
		iv: IV,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7
	});
	var encryptedText = CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
	
	return {
		sendData: "encData=" + encodeURIComponent(encryptedText) + "&ken=" + mkey,
		ApiUrl: sendData.ApiUrl,
		header,
		ktlsetting,
		queueProps: JSON.stringify(ktlsetting)
	}
}


export interface IKtlapi {
	apiurl?: string;
	data?: any;
	action?: string;
	isqueue?: boolean;
	mask?: boolean;
	islist?: boolean,
	opuid?: number | 0,
	routeid?: string
}
/**
 * ktlapi 请求方法
 * @param { IKtlapi } options 请求参数
 * @description
 * - apiurl OT请求方式，非必传
 * - action 接口名称
 * - data 请求参数
 * - islist 是否列表，非必传，默认值：false
 * - mask 设置加载状态(遮罩层)，非必传
 * - opuid 操作人，非必传，默认值：0
 * - isqueue 是否参与请求队列节流，非必传，默认值：true
 * - routeid 路由标识，非必传
 */
export function ktlapi(options: IKtlapi) {
	const {
		action,
		data = {},
		...others
	} = options;
	// 是否显示加载中
	let showLoading = true;

	return new Promise((resolve, reject) => {
		
		// 获取key
		request({
			url: '/apifilter/ApiRoute.ashx?list=false&Encrypt=false',
			data: 'ApiUrl=/Encrypt/GetKey'
		}).then((respKeyData: any) => {
			const key = respKeyData.data.data;
			//console.log('请求Key：' + key)
			// 生成请求参数
			const { sendData, queueProps, ktlsetting, ApiUrl } = makeSendData(action, data, key, others)
			const { isqueue = false } = others;
			// 请求队列
			const { requestQueue } = ktlcache;
			if (isqueue) {
				// 检测请求队列中是否存在
				if (requestQueue.has(sendData + queueProps)) return;
				// 添加请求队列
				requestQueue.add(sendData + queueProps);
			}

			// 设置加载状态(遮罩层)
			// console.log('t1',others);
			// console.log('t2',isUnde(others?.mask));
			if (!isUnde(others?.mask)) {
				showLoading = others.mask;
			}

			try {
				// 显示加载中效果
				// 
				//console.log(options)  
				if (typeof(options.action) != 'undefined') {
					// console.log(1)
					//console.log(options.action);
					// 是否是Command请求
					if (showLoading && isCommandType(ApiUrl)) {
						getApp().globalData.globeList.push({
							"Command": options.action
						});
					}
				} else {

				}
				// console.log('getApp().globalData.globeList', getApp().globalData.globeList)
				if (getApp().globalData.globeList.length == 1) {
					showLoading && uni.showLoading({
						title: "",
						mask: true,
					});
					// console.log(showLoading);
					// console.log('show');
				}
			} catch (e) {}
			// console.log(import.meta)
			//console.log('请求地址：' + HTTP_REQUEST_INFO.API_ROUTER + '?list=' + ktlsetting.islist + '&OU=' + ktlsetting.opuid)
			//console.log('==========================================')
			// 发起请求
			request({
				url: HTTP_REQUEST_INFO.API_ROUTER + '?list=' + ktlsetting.islist + '&OU=' + ktlsetting.opuid,
				data: sendData,
				method: 'POST'
			}).then((resp: any) => {
				try {
					//showLoading && uni.hideLoading();
					for (var i = 0; i < getApp().globalData.globeList.length; i++) {
						if (getApp().globalData.globeList[i]["Command"] == options.action) {
							getApp().globalData.globeList.splice(i, 1);
							break;
						}
					}
					// console.log("getApp().globalData.globeList.length",getApp().globalData.globeList.length);
					if (getApp().globalData.globeList.length == 0) {
						showLoading && uni.hideLoading();
						// console.log(showLoading);
						// console.log('hide');
					}
				} catch (e) {}

				if (resp.statusCode == 200) {
					if (!!resp.data) {
						return resolve(resp.data)
					}
					return reject(resp)
				}
				return reject(resp)
			})
			.catch(err => {
				console.log('catch err', err)

				try {
					uni.showToast({
						icon: "error",
						title: "请求错误"
					})
				} catch (e) {}

				return reject(err)
			})
			.finally(() => {

				showLoading && uni.hideLoading();

				if (isqueue) {
					// 移除请求队列
					requestQueue.remove(sendData + queueProps);
				}
			})
		}).catch(() => {
			showLoading && uni.hideLoading();
			
			try {
				uni.showToast({
					icon: "error",
					title: "请求错误"
				})
			} catch (e) {}
			reject()
		})
	})
}
/** ktlapi 扩展版 */
ktlapi.plus = (options: any) => {

	let defaults: any = {
		method: 'post',
		url: '',
		data: '',
	};

	for (var key in options) {
		defaults[key] = options[key];
	}

	if (typeof defaults.data === 'object') {
		var str = '';
		for (var key in defaults.data) {
			str += key + '=' + defaults.data[key] + '&';
		}
		defaults.data = str.substring(0, str.length - 1);
	}

	defaults.method = defaults.method.toUpperCase();

	return request({
		...defaults
	})
}

// 上传文件
export function uploadFile(file: any) {
	// let language = getBackendLanguage();
	let host_upload = HTTP_REQUEST_INFO.API_UPLOAD_RPODUCT;
	if (process.env.NODE_ENV === 'development') {
		host_upload = HTTP_REQUEST_INFO.API_UPLOAD_DEV;
	}

	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: host_upload + 'file/upload',
			filePath: file.path,
			header: {},
			name: 'file',
			formData: {
				'name': file.name
			},

			success: (res) => {
				let return_data = {};
				// if (typeof(obj) === "object") {
				// 	return_data.data = res.data;
				// } else {
				// 	return_data.data = JSON.parse(res.data);
				// }
				resolve(return_data);
			}
		});
	})
}
